<template>
  <div class="main" style="height: 824px">
    <div style="margin: 5px">
      <el-input v-model="eno" placeholder="请输入编号" :suffix-icon="Search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      <el-input v-model="ename" placeholder="请输入名字" :suffix-icon="Search" style="width: 200px; margin-left: 5px"
                @keyup.enter.native="loadPost"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="danger" style="margin-left: 5px" @click="resetParam">重置</el-button>
      <el-button type="success" style="margin-left: 5px" @click="add" :disabled="user.roleLevel === 2">新增</el-button>
      <el-button type="info" style="margin-left: 5px" @click="exportCsv">导出为CSV文件</el-button>
    </div>
    <el-table :data="tableData" :header-cell-style="{ background: '#f3f6fd', color: '#555' }" :border="true">
      <el-table-column prop="eno" label="员工编号"/>
      <el-table-column prop="ename" label="姓名"/>
      <el-table-column prop="epwd" label="密码"/>
      <el-table-column prop="elevel" label="员工级别">
        <template v-slot:default="scope">
          <el-tag
              :type="scope.row.elevel === 0 ? 'danger' : (scope.row.elevel === 1 ? 'primary' : 'success')"
              disable-transitions>
            {{ scope.row.elevel === 0 ? '董事' : (scope.row.elevel === 1 ? '经理' : '普通员工') }}
          </el-tag>
        </template>
      </el-table-column>
      <!--      <el-table-column prop="sex" label="性别">-->
      <!--        <template v-slot:default="scope">-->
      <!--          <el-tag :type="scope.row.sex === 0 ? 'danger' : (scope.row.sex === 1 ? 'primary' : 'success')"-->
      <!--                  disable-transitions>-->
      <!--            {{ scope.row.sex === 0 ? '未知' : (scope.row.sex === 1 ? '男' : '女') }}-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column prop="age" label="年龄" />-->
      <el-table-column prop="ephone" label="电话"/>
      <el-table-column prop="ewages" label="工资"/>
      <el-table-column prop="eremark" label="备注"/>
      <el-table-column prop="" label="操作">
        <template v-slot:default="scope">
          <el-button size="small" type="success" @click="edit(scope.row)" :disabled="user.roleLevel === 2 || scope.row.elevel < user.roleLevel">编辑</el-button>
          <el-popconfirm title="你确定要删除这个吗?" @confirm="del(scope.row.eno)">
            <template #reference>
              <el-button size="small" type="danger" :disabled="user.roleLevel === 2 || scope.row.elevel < user.roleLevel">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[17]" :small="small"
                   :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   style="bottom: 20px; position: fixed; margin-left: 5px; z-index: 2"/>
    <el-dialog class="el-dialog" v-model="centerDialogVisible" :title="title" width="400px" center @close="resetForm">
      <el-form :model="form" label-width="auto" style="width: 80%; margin-left: 40px;" :rules="rules"
               ref="formRef">
        <el-form-item label="编号" prop="eno">
          <el-input :disabled="title === '编辑'" v-model="form.eno"/>
        </el-form-item>
        <el-form-item label="姓名" prop="ename">
          <el-input v-model="form.ename"/>
        </el-form-item>
        <el-form-item label="密码" prop="epwd">
          <el-input v-model="form.epwd" type="password" placeholder="请输入" show-password/>
        </el-form-item>
        <el-form-item label="级别" prop="elevel">
          <el-radio-group v-model="form.elevel">
            <el-radio :value=0>董事</el-radio>
            <el-radio :value=1>经理</el-radio>
            <el-radio :value=2>普通员工</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话" prop="ephone">
          <el-input v-model="form.ephone"/>
        </el-form-item>
        <el-form-item label="备注" prop="eremark">
          <el-input type="textarea" v-model="form.eremark"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="centerDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="resetFormEditAdd">重置</el-button>
          <el-button type="success" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onBeforeMount, ref} from 'vue';
import axios from 'axios';
import {httpUrl} from '../../main.js';
import {Search} from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';
import Papa from 'papaparse';

const user = ref(JSON.parse(sessionStorage.getItem("CurUser")));
const currentPage = ref(1);
const pageSize = ref(17);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const total = ref(0);
const tableData = ref();
const eno = ref('');
const enoCompare = ref();
const ephoneCompare = ref();
const ename = ref('');
const centerDialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  eno: "",
  ename: "",
  epwd: "",
  elevel: 2,
  ephone: "",
  ewages: 6000,
  eremark: ""
});

const resetFormEditAdd = function () {
  if (title.value === "新增") {
    form.value.eno = ""
  }
  form.value.ename = ""
  form.value.epwd = ""
  form.value.elevel = 2
  form.value.ephone = ""
  form.value.ewages = 6000
  form.value.eremark = ""
}

const resetForm = function () {
  form.value.eno = ""
  form.value.ename = ""
  form.value.epwd = ""
  form.value.elevel = 2
  form.value.ephone = ""
  form.value.ewages = 6000
  form.value.eremark = ""
  // formRef.value.resetFields()
}
const rules = ref({
  eno: [
    {required: true, message: '请输入编号', trigger: 'blur'},
    {max: 10, message: '编号长度不能大于10字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (form.value.eno) {
          if (title.value === "新增") {
            try {
              axios.get(httpUrl + '/employee/findByNo?eno=' + form.value.eno).then((res) => res.data).then((res) => {
                console.log(res);
                if (res.code != 200) {
                  callback()
                } else {
                  callback(new Error("编号已存在"))
                }
              });
            } catch (error) {
              console.log(error);
            }
          }
          if (title.value === "编辑") {
            console.log(enoCompare.value)
            console.log(form.value.eno)
            if (enoCompare.value === form.value.eno) {
              callback()
            } else {
              try {
                axios.get(httpUrl + '/employee/findByNo?eno=' + form.value.eno).then((res) => res.data).then((res) => {
                  console.log(res);
                  if (res.code != 200) {
                    callback()
                  } else {
                    callback(new Error("账号已存在"))
                  }
                });
              } catch (error) {
                console.log(error);
              }
            }
          }
        }
      }, trigger: 'blur'
    }
  ],
  ename: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 100, message: '姓名长度不能小于2个字符,不能大于100字符', trigger: 'blur'},
  ],
  epwd: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 30, message: '密码长度不能小于6个字符,不能大于30字符', trigger: 'blur'},
  ],
  ephone: [
    {required: true, message: '请输入电话', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的电话号码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (form.value.ephone) {
          if (title.value === "新增") {
            try {
              axios.get(httpUrl + '/employee/findByPhone?ephone=' + form.value.ephone).then((res) => res.data).then((res) => {
                console.log(res);
                if (res.code != 200) {
                  callback()
                } else {
                  callback(new Error("手机号已使用"))
                }
              });
            } catch (error) {
              console.log(error);
            }
          }
          if (title.value === "编辑") {
            console.log(ephoneCompare.value)
            console.log(form.value.ephone)
            if (ephoneCompare.value === form.value.ephone) {
              callback()
            } else {
              try {
                axios.get(httpUrl + '/employee/findByPhone?ephone=' + form.value.ephone).then((res) => res.data).then((res) => {
                  console.log(res);
                  if (res.code != 200) {
                    callback()
                  } else {
                    callback(new Error("手机号已使用"))
                  }
                });
              } catch (error) {
                console.log(error);
              }
            }
          }
        }
      }, trigger: 'blur'
    }
  ],
});
const title = ref('')

const handleSizeChange = (val) => {
  console.log(`每页${val}条`);
  currentPage.value = 1;
  pageSize.value = val;
  loadPost();
};

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
  loadPost();
};

const resetParam = () => {
  currentPage.value = 1;
  eno.value = '';
  ename.value = '';
  loadPost();
};

const add = () => {
  title.value = "新增"
  centerDialogVisible.value = true;
};

const doSave = function () {
  try {
    console.log(form.value)
    axios.post(httpUrl + '/employee/save', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '新增成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('新增失败');
        centerDialogVisible.value = false;
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const doMod = function () {
  try {
    axios.post(httpUrl + '/employee/update', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '编辑成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('编辑失败');
        centerDialogVisible.value = false;
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('表单验证成功');
      if (title.value === "编辑") {
        doMod()
      } else {
        doSave()
      }
    } else {
      console.log('表单验证失败');
      return false;
    }
    resetForm()
  });
};

const edit = function (row) {
  enoCompare.value = row.eno
  ephoneCompare.value = row.ephone
  form.value.eno = row.eno
  form.value.ename = row.ename
  form.value.epwd = row.epwd
  form.value.ephone = row.ephone
  form.value.elevel = row.elevel
  form.value.eremark = row.eremark
  title.value = "编辑"
  centerDialogVisible.value = true;
}

const del = function (eno) {
  console.log(eno)
  try {
    axios.get(httpUrl + '/inbuy/findByEno?eno=' + eno).then((res) => res.data).then((res) => {
      if (res.code == 200) {
        ElMessage.error("此项在采购表中有依赖，请删除采购表中的依赖项后操作")
      }
      else {
        axios.get(httpUrl + '/employee/delete?eno=' + eno).then((res) => res.data).then((res) => {
          console.log(res);
          if (res.code == 200) {
            ElMessage({
              message: '删除成功',
              type: 'success'
            });
            loadPost()
          } else {
            ElMessage.error('删除失败');
          }
        });
      }
    })

  } catch (error) {
    console.log(error);
  }
}

const loadGet = async () => {
  try {
    axios.get(httpUrl + '/employee/list').then((res) => res.data).then((res) => {
      console.log(res);
      tableData.value = res;
    });
  } catch (error) {
    console.log(error);
  }
};

const loadPost = async () => {
  console.log(eno.value)
  try {
    axios.post(httpUrl + '/employee/listPage', {
      pageSize: pageSize.value,
      pageNum: currentPage.value,
      param: {
        eno: eno.value,
        ename: ename.value
      }
    }).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        tableData.value = res.data;
        total.value = res.total;
      } else {
        alert('获取数据失败');
      }
    });
  } catch (error) {
    console.log(error);
  }
};

const exportCsv = () => {
  const header = { 'eno': '员工编号', 'ename': '员工姓名', 'epwd': '员工密码', 'ephone': '员工电话', 'elevel': '员工等级', 'ewages': '员工工资', 'eremark': '员工备注'};
  export_csv(header, tableData.value);

  function export_csv(header, data) {
    let list = [];
    for (let i in data) {
      let item = data[i];
      let obj = {};
      for (let key in header) {
        let title = header[key];
        let value = item[key];
        obj[title] = value;
      }
      list.push(obj);
    }

    var csv = Papa.unparse(list);
    let content = new Blob(['\uFEFF' + csv]);
    let urlObject = window.URL || window.webkitURL || window;
    let url = urlObject.createObjectURL(content);
    let el = document.createElement("a");
    el.href = url;
    el.download = "员工表.csv";
    el.click();
    urlObject.revokeObjectURL(url);
  }
};
onBeforeMount(async () => {
  await loadPost();
});
</script>

<style scoped>
.el-dialog {
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
